# {
#     "personExtKey": "100-1097",
#     "personUCode": 10007057,
#     "personCode": "100-1097",
#     "personName": "卢庆乐",
#     "personSex": 1,
#     "personState": 1,
#     "mobilePhone": null,
#     "remarks": "",
#     "isDeleted": false,
#     "deleteTime": null,
#     "modifyTime": "2023-05-19 16:02:59",
#     "sysModifyTime": "2023-05-23 17:46:11"
# }

from module.huada.entity.base_entity import BaseEntity
from plugin import MSsqlClient, Mylogger, MyTime


class VisitorEntity(BaseEntity):
    url = "tunion/get/exterioruser"
    table_name = "visitor"
    create_table = True
    api_data_list = []
    get_time = "2000-01-01 00:00:00"
    order_by = "modifyTime"
    sync_list = []
    write_back_dict = {}

    def __init__(self, **kwargs):
        """
        :param personExtKey: 外部人员主键
        :param personUCode: 外部人员虚拟号
        :param personCode: 外部人员编号
        :param personName: 外部人员姓名
        :param personSex: 外部人员性别
        :param personState: 外部人员状态 1：正常 2：无效
        :param mobilePhone: 外部人员手机号
        :param remarks: 备注
        :param isDeleted: 是否删除
        :param deleteTime: 删除时间
        :param modifyTime: 修改时间
        :param sysModifyTime: 系统修改时间
        """
        self.personExtKey = kwargs.get("personExtKey")
        self.personUCode = kwargs.get("personUCode")
        self.personCode = kwargs.get("personCode")
        self.personName = kwargs.get("personName")
        self.personSex = kwargs.get("personSex")
        self.personState = kwargs.get("personState")
        self.mobilePhone = kwargs.get("mobilePhone")
        self.remarks = kwargs.get("remarks")
        self.isDeleted = kwargs.get("isDeleted")
        self.deleteTime = kwargs.get("deleteTime")
        self.modifyTime = kwargs.get("modifyTime")
        self.sysModifyTime = kwargs.get("sysModifyTime")
        self.isdeal = kwargs.get("isdeal") or 0
        self.id = kwargs.get("id") or 0


    @classmethod
    def do_sync(cls, client: MSsqlClient, objs: list[BaseEntity]):
        """
        同步数据
        :param client:
        :return:
        """
        groupid = add_department("外部人员", client)
        if not groupid:
            Mylogger.error("添加外部人员失败，部门初始化失败")
            return

        result_num = [0, 0]  # 写，删
        for obj in objs:
            result = 0
            usercode = obj.personCode
            recordid = obj.id
            if obj.isDeleted == 'True' or obj.personState == 2:
                sql = f"""
                if exists(select * from acscon_user where usercode = '{usercode}')
                begin
                    delete from acscon_groupmenber where uid = (select id from acscon_user where usercode = '{usercode}')
                    delete from acscon_user where usercode = '{usercode}'
                end
                """
                result = client.execute(sql)
                if result == -1:
                    Mylogger.error(f"删除外部人员失败，未找到人员：{usercode}")
                result_num[1] += 1
            else:
                sql = f"""
                if not exists(select * from acscon_user where usercode = '{usercode}')
                begin
                    declare @id varchar(36) = newid()
                    insert into acscon_user (id,stationid,usercode,name,type,sex,pwd,status,phone,descr)
                    values (@id,'{stationid}','{usercode}','{obj.personName}',1,{obj.personSex},'fhWuQ7Ia6cM=',1,'{obj.mobilePhone}','{obj.personState}')

                    insert into acscon_groupmember (stationid,gid,uid) values ('{stationid}','{groupid}',@id)
                end
                else
                begin
                    update acscon_user set name = '{obj.personName}',sex = {obj.personSex},phone = '{obj.mobilePhone}',descr = '{obj.personState}' where usercode = '{usercode}'
                end
                """
                result = client.execute(sql)
                result_num[0] += 1
        
            if result is not None:
                key = 1 if result > 0 else (int(obj.isdeal) -1)
                if not cls.write_back_dict.get(str(key)):
                    cls.write_back_dict[str(key)] = []

                cls.write_back_dict[str(key)].append(str(recordid))

        Mylogger.info(f"外部人员同步完成，新增{result_num[0]}条，删除{result_num[1]}条")
        return super().do_sync(client, objs)


stationid = 'C9AB162E-4712-E411-976E-7427EA38CA2A'

def add_department(groupname, client: MSsqlClient):
    """
    添加部门
    :param groupname:
    :return:
    """
    sql = f"""
    if not exists(select * from acscon_group where type = 1 and level = 1 and name = '{groupname}')
    begin
        insert into acscon_group (stationid,type, level, name, pid) 
        values ('{stationid}',1, 1, '{groupname}', '{stationid}')
    end
    select id from acscon_group where type = 1 and level = 1 and name = '{groupname}'
    """
    res = client.select_to_dict(sql)
    return res[0]["id"] if res else None